<?php
namespace jy_team2fee;
defined('BY_JYA') or exit('error');
/*
	股东分红计算
	
*/
class commission extends \plugin{
	/*
		生成分红
	*/
	function create($order){
		if(!$this->setting['isopen']){
			return false;
		}
		$this->model('model')->create_feechi($order);
		$this->order=$order;		
		$this->commission_order=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$this->order['mid'],
			'ordersn'=>$this->order['ordersn'],
			'order_price'=>$this->order['price'],
			'commission_money'=>0,
			'red_money'=>0,
			'daili_money'=>0,
			'ping_money'=>0,
			'isgetping'=>0,
			'zhi_money'=>0,
			'jian_money'=>0,
			'pingji_money'=>0,
			'createtime'=>TIMESTAMP,
		);
		//1、默认方式: 除运费和会员折扣(或促销折扣)外其他所有费用全部计算分红；实际支付方式: 只计算实际支付和余额抵扣部分的分红(包括余额支付)
		if($this->setting['commissiontype']==2){
			$this->commission_order['commission_price']=$this->order['price'];
		}else{
			$this->commission_order['commission_price']=$this->order['price']-$this->order['dispatchprice'];
		}
		$member=$this->get('member',array('mid'=>$this->order['mid'],'uniacid'=>$_SESSION['uniacid']));
		if(!$member['id']){
			$member=$this->model('member')->register();
		}
		//门店补贴
		if($member['storemid']){
			$this->create_storefee($member['storemid']);
		}
		$fromuser=$member['mid'];
		$this->gei_mid=$member['gei_mid'];
		//付费时才归属AB
		if($member['fromuser'] && $this->gei_mid==0){
			$this->gei_mid=$this->model('member')->gei_member($member);
		}
		$this->commission_order['teamid']=$fromuser;
		if($member['level_id'] && $member['is_agent']){
			$this->nowlevel=$this->getcolumn('level',array('id'=>$member['level_id']),'level');
		}else{
			$this->nowlevel=0;
		}
		$parameter=array(
			'params'=>array('uniacid'=>$_SESSION['uniacid']),
			'orderby'=>'level asc',
			'limit'=>'1',
		);		
		$levels=$this->get_list('level',$parameter);
		$minlevel=$levels[0]['level'];
		$parameter['orderby']='level desc';
		$levels=$this->get_list('level',$parameter);
		$this->commission_order['maxlevel']=$maxlevel=$levels[0]['level'];
		$levelnum=12;
		//AB线
		if($this->nowlevel==0 && $this->gei_mid>0){
			//感恩奖
			$gei_agent=$this->get('member',array('mid'=>$this->gei_mid,'uniacid'=>$_SESSION['uniacid']));
			$this->lastmoney=0;
			$this->create_redcommission($gei_agent,1);
			//团队奖
			if($gei_agent['level_id']>0 && $this->lastmoney>0){
				$agent=$this->get('member',array('mid'=>$gei_agent['fromuser'],'uniacid'=>$_SESSION['uniacid']));
				$this->create_redcommission($agent,4);
			}
		}
		$this->lastmoney=0;
		for($i=0;$i<$levelnum;$i++){
				if(!$fromuser){
					break;
				}
				$lastmoney2=$this->lastmoney;
				$agent=$this->get('member',array('mid'=>$fromuser,'uniacid'=>$_SESSION['uniacid']));
				$fromuser=$agent['fromuser'];
				$level=$this->getcolumn('level',array('id'=>$agent['level_id']),'level');
				$level=$level?:0;
				//团队奖
				if($this->nowlevel && $level && $lastmoney2>0){
					$this->create_redcommission($agent,4);
				}
				$this->lastmoney=0;
				if(!$i){
					//复购奖励,先注销
					//$this->create_redcommission($agent,6);
				}
				//推荐奖励（极差）。
				if($i==1){
					//直推奖励
					$this->create_redcommission($agent,0);
					if(!$member['is_agent']){
						$this->model('member')->up_agent($member);
					}
				}
				$this->nowlevel=$level;
				//如果他的上级是我
				$ta_agent_id=$this->getcolumn('member',array('mid'=>$fromuser),'fromuser');
				if($ta_agent_id==$agent['mid']){
					break;
				}
		}
		//生成分销订单
		if($this->commission_order['isarea']){
			$indata=$this->commission_order;
			unset($indata['isarea']);
			unset($indata['maxlevel']);
			unset($indata['red_money']);
			unset($indata['commission_jifen']);
			unset($indata['isgetping']);
			unset($indata['zhi_money']);
			unset($indata['jian_money']);
			unset($indata['pingji_money']);
			$this->insert('order',$indata);
		}
		//自购升级
		if($member['mid']){
			$this->model('member')->update_agent_level($member['mid'],true);
		}
		return true;
	}
	/*
		级差分佣type=1;lastmoney2,晋级奖励的感恩
	*/
	function create_redcommission($agent,$type=0,$lastmoney2=0){
			if(!$agent['is_agent']){
				return false;
			}
			$commission_level=$agent['level_id'];
			if(!$agent['level_id']){
				$level=$this->plugin_setting('default_level');
				$level_id=0;
				$pingcommission_per=$level['ping_per'];
				if($type==0|| $type==6){
					$commission_per=$level['zhi_per'];
				}elseif($type==1){
					$commission_per=$level['jian_per'];
				}elseif($type==2){
					$commission_per=$level['red_per'];
				}
				
				$pj_per=$level['pingji_per'];
				if(!$agent['isjiedong']){
					$dong_per=$level['dong_per'];
				}
			}else{
				$level=$this->get('level',array('id'=>$agent['level_id'],'uniacid'=>$_SESSION['uniacid']));
				$level['setdata']=json_decode($level['setdata'],true);
				$level_id=$level['id'];
				$pingcommission_per=$level['ping_per'];
				if($type==0|| $type==6){
					$commission_per=$level['zhi_per'];
				}elseif($type==1){
					$commission_per=$level['jian_per'];
				}elseif($type==2){
					$commission_per=$level['red_per'];
				}
				$pj_per=$level['pingji_per'];
				if(!$agent['isjiedong']){
					$dong_per=$level['dong_per'];
				}
			}
			$money=0;
			$pjmoney=0;
			$jifen=0;
			$order_price=$this->commission_order['commission_price'];
			$remark=array(
				'level_id'=>$level_id,
				'order_price'=>$order_price,
				'goods_commission'=>array(),
			);
			//先检查是否存在商品独立分红规则，如果存在则对订单相应商品部分金额单独计算分红
			$this->needorder=false;
			foreach($this->order['goods'] as $goods){
				$ignore=$this->get('goods',array('goods_id'=>$goods['goodsid'],'uniacid'=>$_SESSION['uniacid']));
				if(!$ignore['id']){
					$this->needorder=true;
					continue;
				}
				if($ignore['ignore']){
					$goods_commission=array();
					$order_price=$order_price-$goods['total_price'];
					continue;
				}else{
					$goods_commission=$ignore['commissions']?json_decode($ignore['commissions'],true):array();
				}
				$order_price=$order_price-$goods['total_price'];
				foreach($goods_commission as $gc){
						if($gc['level_id']==0){
							if($type==0|| $type==6){
								$demogoods_commission_per=$gc['zhi_per'];
							}elseif($type==1){
								$demogoods_commission_per=$gc['jian_per'];
							}elseif($type==2){
								$demogoods_commission_per=$gc['red_per'];
							}
							$demogoods_pj_per=$gc['pingji_per'];
							$demogoodsjifen_per=$gc['jindoufee'];
						}
						if($gc['level_id']!=$level_id){
							continue;
						}else{
							if($type==0|| $type==6){
								$goods_commission_per=$gc['zhi_per'];
							}elseif($type==1){
								$goods_commission_per=$gc['jian_per'];
							}elseif($type==2){
								$goods_commission_per=$gc['red_per'];
							}
							$goods_pj_per=$gc['pingji_per'];
							$goodsjifen_per=$gc['jindoufee'];
							break;
						}
				}
				$goods_commission_per=$goods_commission_per?:$demogoods_commission_per;
				//先注销，不按默认走；
				//$goods_commission_per=$goods_commission_per?:$commission_per;
				$goods_pj_per=$goods_pj_per?:$demogoods_pj_per;
				//$goods_pj_per=$goods_pj_per?:$pj_per;	
				if(substr($goods_commission_per,-1)=='%'){
						$goods_commission_money=($goods['total_price']*substr($goods_commission_per,0,-1))/100;
				}else{
						$goods_commission_money=$goods_commission_per*$goods['total'];
				}
				//if(substr($goods_pj_per,-1)=='%'){
				//		$goods_pj_money=($goods['total_price']*substr($goods_pj_per,0,-1))/100;
				//}else{
				//		$goods_pj_money=$goods_pj_per*$goods['total'];
				//}
				$money+=$goods_commission_money;
				//$pjmoney+=$goods_pj_money;
				$goodsjifen_per=$goodsjifen_per?:$demogoodsjifen_per;
				//$goodsjifen_per=$goodsjifen_per?:$jifen_per;	
				if(substr($goodsjifen_per,-1)=='%'){
						$order_commission_jifen=($goods['total_price']*substr($goodsjifen_per,0,-1))/100;
				}else{
						$order_commission_jifen=$goodsjifen_per*$goods['total'];
				}
				$order_commission_jifen -=$this->commission_order['commission_jifen'];
				$jifen +=$order_commission_jifen;
				$remark['goods_commission'][]=array('goods_id'=>$goods['goodsid'],'total_price'=>$goods['total_price'],'total'=>$goods['total'],'commission_per'=>$goods_commission_per,'commission_money'=>$goods_commission_money);
			}
			if($order_price>0 || ($this->order['goods'] && $this->needorder)){
				if(substr($commission_per,-1)=='%'){
						$order_commission_money=($order_price*substr($commission_per,0,-1))/100;
				}else{
						$order_commission_money=$commission_per;
				}
				$money+=$order_commission_money;
				if(substr($jifen_per,-1)=='%'){
						$commission_jifen =($order_price*substr($jifen_per,0,-1))/100;
				}else{
						$commission_jifen =$jifen_per*$goods['total'];
				}
				$commission_jifen -=$this->commission_order['commission_jifen'];
				$jifen +=$commission_jifen;
				$remark['order_commission']=array('order_price'=>$order_price,'commission_per'=>$commission_per,'commission_money'=>$order_commission_money);
			}
			if($type==0 || $type==6){
				$money -=$this->commission_order['zhi_money'];
			}elseif($type==1){
				$money -=$this->commission_order['jian_money'];
			}elseif($type==2){
				$money -=$this->commission_order['red_money'];
			}elseif($type==4){
				if(substr($pj_per,-1)=='%'){
					$order_pj_money=($this->lastmoney*substr($pj_per,0,-1))/100;
				}else{
					$order_pj_money=$pj_per;
				}
				$pjmoney+=$order_pj_money;
				$pjmoney -=$this->commission_order['pingji_money'];
			}
			$remark['commission_money']=$money;
			if(($type!=4 && $money>0) || ($type==4 && $pjmoney>0)){
				$moneyfee=$type==4?$pjmoney:$money;
				if($type==0 || $type==6){
					$this->commission_order['zhi_money']+=$moneyfee;
					$this->lastmoney=$moneyfee;
				}elseif($type==1){
					$this->commission_order['jian_money']+=$moneyfee;
					$this->lastmoney=$moneyfee;
				}elseif($type==2){
					$this->commission_order['red_money']+=$moneyfee;
				}elseif($type==4){
					$this->commission_order['pingji_money']+=$moneyfee;
				}
				$this->commission_order['commission_money']+=$moneyfee;
				$this->commission_order['commission_jifen']+=$jifen;
				//感恩才冻结
				if($dong_per && $type==1){
					if(substr($dong_per,-1)=='%'){
						$dong_fee=($moneyfee*substr($dong_per,0,-1))/100;
					}else{
						$dong_fee=$dong_per;
					}
					if($dong_fee>0){
						$moneyfee -=$dong_fee;
					}
				}
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'level'=>$level_id,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$moneyfee>0?$moneyfee:0,
					'jifen'=>$jifen,
					'dong_fee'=>$dong_fee,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
					'type'=>$type,
				);
				$this->insert('commission',$new_commission);
			}
			//判断是否存在股东
			$this->commission_order['isarea']=true;
	}
	/*
		门店补贴
	*/
	public function create_storefee($storemid){
		if($this->setting['storeis_open']!=1 || !$this->setting['storered_rate']){
			return false;
		}
		$storered_rate=$this->setting['storered_rate'];
		$order_price=$this->order['price'];
		//先检查是否存在商品独立分红规则，如果存在则对订单相应商品部分金额单独计算分红
		$needorder=false;
		foreach($this->order['goods'] as $goods){
				$ignore=$this->get('goods',array('goods_id'=>$goods['goodsid'],'uniacid'=>$_SESSION['uniacid']));
				if($ignore['nostore']){
					$order_price -=$goods['total_price'];
				}else{
					$needorder=true;
				}
		}
		if($needorder && $order_price>0){
			if(substr($storered_rate,-1)=='%'){
				$moneyfee =($order_price*substr($storered_rate,0,-1))/100;
			}else{
				$moneyfee =$storered_rate;
			}
		}
		$agent=$this->get('member',array('mid'=>$storemid,'uniacid'=>$_SESSION['uniacid']));
		if($moneyfee >0){
			$new_commission=array(
						'uniacid'=>$_SESSION['uniacid'],
						'mid'=>$agent['mid'],
						'level'=>$agent['level_id'],
						'ordersn'=>$this->order['ordersn'],
						'money'=>$moneyfee>0?$moneyfee:0,
						'jifen'=>0,
						'dong_fee'=>0,
						'remark'=>'门店补贴',
						'createtime'=>TIMESTAMP,
						'status'=>$this->setting['is_jiesuan']?:0,
						'type'=>2,
			);
			$this->insert('commission',$new_commission);
		}
		return true;
	}
	/*
		订单完成时，把分红状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order){
		$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('ordersn'=>$order['ordersn'],'status'=>0));
	}
	/*
		解冻
	*/
	public function jie_dong($mid=0){
		$mid=$mid?:$_SESSION['uid'];
		if(!$mid){
			return false;
		}
		$params=array('dong_fee >'=>0,'isjiedong'=>0,'uniacid'=>$_SESSION['uniacid'],'mid'=>$mid);
		$dong_fee=$this->getsum('commission',$params,'dong_fee');
		if($dong_fee<=0){
			return false;
		}
		$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$mid,
					'money'=>$dong_fee,
					'remark'=>'解冻分红',
					'createtime'=>TIMESTAMP,
					'status'=>1,
					'type'=>2,
		);
		$this->insert('commission',$new_commission);
		$this->update('commission',array('isjiedong'=>1),$params);
		$this->update('member',array('isjiedong'=>1),array('mid'=>$mid));
		return true;
	}
	/*
		创建结算单
	*/
	public function create_balance($mid,$post=array()){
		$type=intval($post['type']);
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
		}
		//获取可结算分红
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		if($type){
			$params['type']=$type;
			$isgetfee=$this->model('member')->check_isgetfee($mid,$type);
			if($isgetfee){
				exi('您已结算过了该奖金！不能再结算！','error');
			}
		}else{
			$params['type <=']=3;
		}
		$commissions=$this->getall('commission',$params);
		if(!$commissions){
			exi('没有可结算的分红！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		$jifen=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
			$jifen+=$commission['jifen'];
		}
		//结算最低分红检测
		if($money<$this->setting['balance_fee']){
			exi('满￥'.$this->setting['balance_fee'].'才可结算！','error');
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'jifen'=>$jifen,
			'pay_type'=>$post['pay_type'],
			'realname'=>$post['realname'],
			'alipay'=>$post['alipay'],
			'bankname'=>$post['bankname'],
			'bankcard'=>$post['bankcard'],
			'createtime'=>TIMESTAMP,
			'fee_type'=>$type,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('commission',$update,array('id'=>$commission['id']));
		}
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn']);
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		if($balance['jifen']>0){
			cfc('core')->member_credit($balance['mid'],'credit1',$balance['jifen'],true,$this->plugin_name,$remark='佣金转积分');
		}
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销分红打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn){
		$params=array(
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'remark'=>'代理商分红发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，分红规则【{$goods['commission_per']}】，分销分红【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='';
		}
		$remark['level_title']=pdo_getcolumn('jy_team2fee_level',array('uniacid'=>$_SESSION['uniacid'],'level'=>$remark['level_id']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
股东等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，分红等级【{$remark['commission_level']}】，订单总价【{$remark['order_price']}】
商品独立分红：
{$goods_str}
订单分红：
除去设置独立分红的商品外订单金额【{$remark['order_commission']['order_price']}】，分红规则【{$remark['order_commission']['commission_per']}%】，分销分红【{$remark['order_commission']['commission_money']}】
分红总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
}